package com.lzxuni.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.lzxuni.common.constant.ConstantEnum;
import com.lzxuni.modules.common.entity.FileEntity;

import java.net.URL;
import java.util.Date;
import java.util.List;

public class OSSUtil {
    static final OSSClient ossClient = new OSSClient(ConstantEnum.OSSEnum.OSS_ENDPOINT.getValue(), ConstantEnum.OSSEnum.ACCESS_ID.getValue(),
            ConstantEnum.OSSEnum.ACCESS_KEY.getValue());

    public static String getUrl(String key){

        /*OSSClient ossClient = new OSSClient(ConstantEnum.OSSEnum.OSS_ENDPOINT.getValue(), ConstantEnum.OSSEnum.ACCESS_ID.getValue(),
                ConstantEnum.OSSEnum.ACCESS_KEY.getValue());*/
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(ConstantEnum.OSSEnum.BUCKET_NAME.getValue(), key);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        ossClient.shutdown();
        return url.toString();
    }

    public static String getUrlSpath(String key){

         /*OSSClient ossClient = new OSSClient(ConstantEnum.OSSEnum.OSS_ENDPOINT.getValue(), ConstantEnum.OSSEnum.ACCESS_ID.getValue(),
                ConstantEnum.OSSEnum.ACCESS_KEY.getValue());*/
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        String style = "image/resize,p_80";
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(ConstantEnum.OSSEnum.BUCKET_NAME.getValue(), key);
        generatePresignedUrlRequest.setExpiration(expiration);
        generatePresignedUrlRequest.setProcess(style);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        ossClient.shutdown();
        return url.toString();
    }

    public static List<FileEntity> list(List<FileEntity> fileEntities){
        if(fileEntities != null && fileEntities.size()>0){
            for(FileEntity fileEntity : fileEntities){
                if(fileEntity.getUrlPath() != null && !"".equals(fileEntity.getUrlPath()))
                    fileEntity.setUrlPath(getUrl(fileEntity.getUrlPath()));
                if(fileEntity.getUrlsPath() != null && !"".equals(fileEntity.getUrlsPath()))
                    fileEntity.setUrlsPath(getUrlSpath(fileEntity.getUrlsPath()));
            }
        }
        return fileEntities;
    }
}
